using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Read.API.Applications.Commands.customers;
using SupplierCustomerManagement.Read.API.Dtos;

namespace SupplierCustomerManagement.Read.API.Applications.CommandHandlters.customers
{
    /// <summary>
    /// 获取客户列表查询处理器
    /// </summary>
    public class GetCustomersQueryHandler : IRequestHandler<GetCustomersQuery, ApiPaging<CustomerListDto>>
    {
        private readonly IBaseRepository<Customer> _customerRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<GetCustomersQueryHandler> _logger;

        public GetCustomersQueryHandler(
            IBaseRepository<Customer> customerRepository,
            IMapper mapper,
            ILogger<GetCustomersQueryHandler> logger)
        {
            _customerRepository = customerRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取客户列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>分页查询结果</returns>
        public async Task<ApiPaging<CustomerListDto>> Handle(GetCustomersQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始查询客户列表，页码: {PageIndex}, 每页大小: {PageSize}", 
                    request.PageIndex, request.PageSize);

                // 构建查询条件
                var query = _customerRepository.GetAll()
                    .Where(c => !c.IsDeleted); // 排除已删除的记录

                // 应用筛选条件
                query = ApplyFilters(query, request);

                // 获取总数量
                var totalCount = await query.CountAsync(cancellationToken);

                // 计算总页数
                var pageCount = (int)Math.Ceiling((double)totalCount / request.PageSize);

                // 分页查询
                var customers = await query
                    .OrderByDescending(c => c.CreatedTime) // 按创建时间倒序排列
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射到DTO
                var customerDtos = _mapper.Map<List<CustomerListDto>>(customers);

                _logger.LogInformation("成功查询客户列表，总数量: {TotalCount}, 当前页数量: {CurrentPageCount}", 
                    totalCount, customerDtos.Count);

                return new ApiPaging<CustomerListDto>
                {
                    code = ResultEnumCode.Ok,
                    message = "查询成功",
                    data = default,
                    TotalCount = totalCount,
                    PageCount = pageCount,
                    PageData = customerDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询客户列表时发生异常");
                
                return new ApiPaging<CustomerListDto>
                {
                    code = ResultEnumCode.fails,
                    message = $"查询客户列表时发生异常: {ex.Message}",
                    data = default,
                    TotalCount = 0,
                    PageCount = 0,
                    PageData = new List<CustomerListDto>()
                };
            }
        }

        /// <summary>
        /// 应用筛选条件
        /// </summary>
        /// <param name="query">查询对象</param>
        /// <param name="request">查询请求</param>
        /// <returns>应用筛选条件后的查询对象</returns>
        private IQueryable<Customer> ApplyFilters(IQueryable<Customer> query, GetCustomersQuery request)
        {
            // 客户编号模糊查询
            if (!string.IsNullOrWhiteSpace(request.CustomerCode))
            {
                query = query.Where(c => c.CustomerCode.Contains(request.CustomerCode));
            }

            // 客户名称模糊查询
            if (!string.IsNullOrWhiteSpace(request.Name))
            {
                query = query.Where(c => c.Name.Contains(request.Name));
            }

            // 客户类型精确查询
            if (!string.IsNullOrWhiteSpace(request.Type))
            {
                query = query.Where(c => c.Type == request.Type);
            }

            // 所属行业模糊查询
            if (!string.IsNullOrWhiteSpace(request.Industry))
            {
                query = query.Where(c => c.Industry != null && c.Industry.Contains(request.Industry));
            }

            // 使用状态精确查询
            if (!string.IsNullOrWhiteSpace(request.Status))
            {
                query = query.Where(c => c.Status == request.Status);
            }

            // 是否归档
            if (request.IsArchived.HasValue)
            {
                query = query.Where(c => c.IsArchived == request.IsArchived.Value);
            }

            return query;
        }
    }
}
